import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shake_animation_widget/shake_animation_widget.dart';

void main() => runApp(RootApp());

// 定义根目录Wigdget
class RootApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 根视图
    return MaterialApp(
      // theme: ThemeData(primaryColor: Colors.white),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 1. 点击空白处 隐藏键盘 与输入焦点
  FocusNode _userNameFocusNode = new FocusNode();
  FocusNode _userPasswordFocusNode = new FocusNode();
  TextEditingController _userNameTextController = new TextEditingController();
  TextEditingController _userPasswordTextController =
      new TextEditingController();
  ShakeAnimationController _userNameShakeController =
      new ShakeAnimationController();
  ShakeAnimationController _userPasswordShakeController =
      new ShakeAnimationController();
  // 用户名密码流控制器
  // ignore: close_sinks
  StreamController<String> _userNameStreamController =
      new StreamController(); // ignore: close_sinks
  StreamController<String> _userPasswordStreamController =
      new StreamController();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        hideInputFocus();
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text("textButton"),
        ),
        body: buildBody(),
      ),
    );
  }

  Widget buildBody() {
    return Container(
      margin: EdgeInsets.all(30),
      width: double.infinity,
      child: Column(
        children: [
          buildUserNameWidget(),
          SizedBox(height: 30),
          buildUserPasswordWidget(),
          SizedBox(height: 30),
          buildLoginButton()
        ],
      ),
    );
  }

// 需要安装 shake_animation_widget: ^2.1.2 这个依赖
  Widget buildUserNameWidget() {
    return StreamBuilder<String>(
      stream: _userNameStreamController.stream,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return ShakeAnimationWidget(
          // 抖动方式 左右抖动
          shakeAnimationType: ShakeAnimationType.LeftRightShake,
          // 默认不开启
          isForward: false,
          // 抖动动画控制器
          shakeAnimationController: _userNameShakeController,
          child: TextField(
            // 控制器
            controller: _userNameTextController,
            // 焦点控制
            focusNode: _userNameFocusNode,
            // 边框装饰
            decoration: InputDecoration(
              errorText: snapshot.data,
              labelText: "用户名",
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(10),
                ),
              ),
            ),
            onSubmitted: (String value) {
              if (checkUserName()) {
                // 验证成功 跳转密码输入框
                _userNameFocusNode.unfocus();
                FocusScope.of(context).requestFocus(_userPasswordFocusNode);
              } else {
                // 如果校验不成功
                // 用户名输入框重新获取输入焦点
                FocusScope.of(context).requestFocus(_userNameFocusNode);
              }
            },
          ),
        );
      },
    );
  }

  Widget buildUserPasswordWidget() {
    return StreamBuilder<String>(
      stream: _userPasswordStreamController.stream,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return ShakeAnimationWidget(
          // 抖动方式 左右抖动
          shakeAnimationType: ShakeAnimationType.LeftRightShake,
          // 默认不开启
          isForward: false,
          // 抖动动画控制器
          shakeAnimationController: _userPasswordShakeController,
          child: TextField(
            // 控制器
            controller: _userPasswordTextController,
            // 焦点控制
            focusNode: _userPasswordFocusNode,
            // 边框装饰
            decoration: InputDecoration(
              errorText: snapshot.data,
              labelText: "密码",
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(10),
                ),
              ),
            ),
            onSubmitted: (String value) {
              if (checkUserPassword()) {
                // 验证成功 跳转密码输入框
                _userPasswordFocusNode.unfocus();
                // FocusScope.of(context).requestFocus(_userPasswordFocusNode);
              } else {
                // 如果校验不成功
                // 用户名输入框重新获取输入焦点
                FocusScope.of(context).requestFocus(_userPasswordFocusNode);
              }
            },
          ),
        );
      },
    );
  }

  bool checkUserName() {
    // 获取输入的用户名
    String username = _userNameTextController.text;
    if (username.length == 0) {
      // 错误提示
      _userNameStreamController.add("请输入用户名");
      // 添加抖动效果
      _userNameShakeController.start();
      return false;
    } else {
      // 消除错误提示
      _userNameStreamController.add(null);
      return true;
    }
  }

  bool checkUserPassword() {
    // 获取输入的用户名
    String username = _userPasswordTextController.text;
    if (username.length == 0) {
      // 错误提示
      _userPasswordStreamController.add("请输入密码");
      // 添加抖动效果
      _userPasswordShakeController.start();
      return false;
    } else {
      // 消除错误提示
      _userPasswordStreamController.add(null);
      return true;
    }
  }

// 构建登录按钮+功能
  Widget buildLoginButton() {
    return Container(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: () {
          loginButtonFunction();
        },
        child: Text("登录"),
      ),
    );
  }

  void loginButtonFunction() {
    hideInputFocus();
    bool checkUserPasswordB = checkUserPassword();
    bool checkUserNameB = checkUserName();
    if (checkUserPasswordB && checkUserNameB) {
      // 进行后续操作 TODO
    }
  }

  void hideInputFocus() {
    // 隐藏键盘
    SystemChannels.textInput.invokeMethod("TextInput.hide");
    // 隐藏输入焦点
    _userNameFocusNode.unfocus();
    _userPasswordFocusNode.unfocus();
  }
}
